//
//  MyHistoryViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/8.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MyHistoryViewController.h"
#import "MyHistoryTableViewCell.h"
#import "ShoppingProductDetailViewController.h"
static NSString * cellIndentifier = @"MyHistoryTableViewCell";

@interface MyHistoryViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIButton *deleteButton;

@property(nonatomic,assign)BOOL ifDelete;

@property(nonatomic,strong)NSMutableArray * choseArray;
@property(nonatomic,strong)NSMutableArray * myHistorys;
@end

@implementation MyHistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _ifDelete = NO;
    _myHistorys = [NSMutableArray array];
    _choseArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    [self.tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _tableView.scrollEnabled = YES;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
}
- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getMyHistory];
        });
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.myHistorys.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getMyHistory];
        });
    }
    
}


#pragma mark === 获取我的足迹
- (void)getMyHistory{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryBrowsingHistory withHttpType:@"POST" withTag:SX_SX_queryBrowsingHistory];


}

#pragma mark == 编辑删除
- (IBAction)delete:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        _ifDelete = YES;
        
        [UIView animateWithDuration:0.5 animations:^{
            _deleteButton.frame = flexibleFrame(CGRectMake(0, 526, 320, 42), YES);
        }];
        _tableView.frame = flexibleFrame(CGRectMake(0, 64, 320, 504-42), YES);
    }else{
        _ifDelete = NO;
        [UIView animateWithDuration:0.5 animations:^{
            _deleteButton.frame = flexibleFrame(CGRectMake(0, 568, 320, 42), YES);
        }];
        _tableView.frame = flexibleFrame(CGRectMake(0, 64, 320, 504), YES);
    }
    [_choseArray removeAllObjects];
    [_tableView reloadData];
}

#pragma mark  == 确认删除
- (IBAction)sureDelect:(id)sender {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    NSString * mgbIds = @"";
    for (NSIndexPath * path in _choseArray) {
        NSString * mgbId = _myHistorys[path.row][@"mgbh_id"];
        if (path != [_choseArray lastObject]) {
            mgbId = [NSString stringWithFormat:@"%@,",_myHistorys[path.row][@"mgbh_id"]];
        }
        mgbIds = [mgbIds stringByAppendingString:mgbId];
    }
    [dic setObject:mgbIds forKey:@"mgbhId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_deleteBrowsingHistory withHttpType:@"POST" withTag:SX_SX_deleteBrowsingHistory];

    
}


- (IBAction)goHome:(id)sender {
    [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"ifLogin"];
    [self.navigationController  popViewControllerAnimated:YES];
}



#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 107*VerticalRatio();
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _myHistorys.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyHistoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell= [[MyHistoryTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        
    }
    
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    if (_ifDelete == YES) {
        [UIView animateWithDuration:0.5 animations:^{
            cell.infoView.frame = flexibleFrame(CGRectMake(40, 0, 320, 101), YES);
        }];
    }else{
        [UIView animateWithDuration:0.5 animations:^{
            cell.infoView.frame = flexibleFrame(CGRectMake(0, 0, 320, 101), YES);
        }];
    }
    
    
        NSString * image = _myHistorys[indexPath.row][@"simaImagUri"];
        if (image.length>0) {
            [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:image]];
        }
    cell.goodsName.frame = flexibleFrame(CGRectMake(100, 17, 212, 15), YES);
    cell.goodsName.text = [NSString stringWithFormat:@"%@",_myHistorys[indexPath.row][@"mgoo_name"]];
    cell.goodsName.numberOfLines = 0;
    [cell.goodsName sizeToFit ];
    
    cell.goodsPrice.text = [NSString stringWithFormat:@"￥%@",_myHistorys[indexPath.row][@"mgooPublishPrice"]];
    if([_myHistorys[indexPath.row][@"mgooOrginalPrice"] isEqualToString:@""]){
        cell.goodsOldPrice.text  = [NSString stringWithFormat:@"%@",_myHistorys[indexPath.row][@"mgooOrginalPrice"]];
    }else{
        cell.goodsOldPrice.text  = [NSString stringWithFormat:@"￥%@",_myHistorys[indexPath.row][@"mgooOrginalPrice"]];
    }
    //优惠劵，满减
    cell.goodsYouhuijuanLabel.hidden = YES;
    cell.goodsManjianLabel.hidden = YES;
    NSString *mallStoreCoupon = [NSString stringWithFormat:@"%@",_myHistorys[indexPath.row][@"mallStoreCoupon"]];
    if ([mallStoreCoupon isEqualToString:@"1"]) {
        cell.goodsYouhuijuanLabel.hidden = NO;
    }
    NSString *storeOfflinePromotion = [NSString stringWithFormat:@"%@",_myHistorys[indexPath.row][@"storeOfflinePromotion"]];
    if ([storeOfflinePromotion isEqualToString:@"1"]) {
        cell.goodsManjianLabel.hidden = NO;
    }
    
    
    cell.choseComplect = ^(NSString * str){
        if ([str isEqualToString:@"1"]) {
             [_choseArray addObject:indexPath];
        }else{
            [_choseArray removeObject:indexPath];
        }
        [_deleteButton setTitle:[NSString stringWithFormat:@"删除(%ld)",_choseArray.count] forState:UIControlStateNormal];
    };
    
      cell.choseButton.selected = NO;
    for (NSIndexPath * path in _choseArray) {
        if (path == indexPath) {
            cell.choseButton.selected = YES;
        }
        
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    ShoppingProductDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ShoppingProductDetail"];
    page.goodsId = _myHistorys[indexPath.row][@"mgoo_Id"];
    [self.navigationController   pushViewController:page animated:YES];
    

}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag == SX_SX_queryBrowsingHistory){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
//                _totle = [database[@"result"][@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.myHistorys removeAllObjects];
                }
//                NSArray *arr = database[@"result"][@"pageRecord"];
                 NSArray *arr = database[@"result"];
                for (id entity in arr) {
                    [self.myHistorys addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });
            
        }
        
    }else if (tag == SX_SX_deleteBrowsingHistory){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
          [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc]init];
            for (NSIndexPath * path in _choseArray) {
                [indexSet addIndex:path.row];
            }
            [_myHistorys removeObjectsAtIndexes:indexSet];
            [_choseArray removeAllObjects];
            _ifDelete = NO;
            [UIView animateWithDuration:0.5 animations:^{
                _deleteButton.frame = flexibleFrame(CGRectMake(0, 568, 320, 42), YES);
            }];
            _tableView.frame = flexibleFrame(CGRectMake(0, 64, 320, 504), YES);
            [_tableView reloadData];
            
        }
        
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
